package com.zzw.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzw.entity.User;
import com.zzw.mapper.dao.UserDAOMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.cache.annotation.*;
import tk.mybatis.mapper.entity.Condition;

import java.util.List;

@Service
@CacheConfig(cacheNames = "user")
public class UserService {
    @Autowired
    private UserDAOMapper userDAOMapper;

    @CachePut(key = "#root.targetClass+':'+#p0.id", unless = "#result eq null")  //#p0表示第一个参数
    public User insertUser(User u) {
        userDAOMapper.insert(u);
        return u;
    }

    @CachePut(key = "#root.targetClass+':'+#p0.id", unless = "#result eq null")
    public User updateUser(User u) {
        userDAOMapper.updateByPrimaryKey(u);
        return u;
    }

    @CacheEvict(key = "#root.targetClass+':'+#p0.id")  //删除缓存名称为userCache,key等于指定的id对应的缓存
    public int deleteById(User user) {
        return userDAOMapper.delete(user);
    }

    @Cacheable(key = "#root.targetClass+':'+#p0.id", unless = "#result eq null") // @Cacheable 会先查询缓存，如果缓存中存在，则不执行方法
    public User selectOne(User user) {
        return userDAOMapper.selectOne(user);
    }

    @CacheEvict(allEntries = true)
    public int deleteAll() {
        return userDAOMapper.delete(null);
    }

    @CacheEvict(allEntries = true)
    public int deleteByIds(String ids) {
        return userDAOMapper.deleteByIds(ids);
    }

    public List<User> findUserByCondition() {
        Condition condition = new Condition(User.class);
        condition.createCriteria().andCondition("username like 'tes%'");
        return userDAOMapper.selectByCondition(condition);
    }

    public int insertList(List<User> users) {
        return userDAOMapper.insertList(users);
    }

    public List<User> selectByIds(String ids) {
        return userDAOMapper.selectByIds(ids);
    }

    public PageInfo<User> queryPage(String userName, int pageNum, int pageSize) {
        Page<User> page = PageHelper.startPage(pageNum, pageSize);
        //PageHelper会自动拦截到下面这查询sql
        List<User> users = this.userDAOMapper.listByPage(userName);
        return page.toPageInfo();
    }

    //测试事务
    //注意：方法的@Transactional会覆盖类上面声明的事务
    //Propagation.REQUIRED ：有事务就处于当前事务中，没事务就创建一个事务
    //isolation=Isolation.DEFAULT：事务数据库的默认隔离级别
    public void batchDealWithUsers() {
        //删除全部
        this.userDAOMapper.delete(null);
        //新增
        User u = new User();
        u.setId(123456);
        u.setUsername("张三11111");
        u.setPassword("12adfdfasdfd111111111111");
        this.userDAOMapper.insert(u);
        //制造异常
        throw new RuntimeException("事务异常测试");
    }
}
